﻿using System;
using System.Collections.Generic;
using System.Text;
using NHibernate;
using NHibernate.Cfg;

namespace DASwindles
{
    public class DAHelper
    {
        private Configuration _configuration;
        private static ISessionFactory _sessionFactory;
        private static ISession _session;
        private static ITransaction _transaction;

        public  DAHelper()
        {
            if (_sessionFactory == null)
            {
            if (_configuration == null)
                {
                    _configuration = new Configuration();
                    string connectionString = System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
                    _configuration.SetProperty(NHibernate.Cfg.Environment.Dialect, "NHibernate.Dialect.SQLiteDialect");
                    _configuration.SetProperty(NHibernate.Cfg.Environment.ConnectionDriver, "NHibernate.Driver.SQLite20Driver");
                    _configuration.SetProperty(NHibernate.Cfg.Environment.ConnectionString, connectionString);
                    _configuration.SetProperty(NHibernate.Cfg.Environment.ProxyFactoryFactoryClass, "NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle");

                    _configuration.AddAssembly("OBSwindles");
                }
            
                _sessionFactory = _configuration.BuildSessionFactory();
                _session = _sessionFactory.OpenSession();
            }
        }

        public static ISession getSession()
        {
            if ((_session == null) || (_session != null && _session.IsConnected == false))
            {
                _session = _sessionFactory.OpenSession();
            }
            return _session;
        }

        public void beginTransaction()
        {
            if (_transaction != null && _transaction.IsActive)
            {
                _transaction.Rollback();
            }
            _transaction = getSession().BeginTransaction();
        }

        public void commitTransaction()
        {
            _transaction.Commit();
        }

        public void rollbackTransaction()
        {
            _transaction.Rollback();
        }
       

    }
}
